
// curriculum_package/pages/myCurriculum/myCurriculum.ts
import {getClassList,getClassListForRange} from '../../../api/member'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isTk:false, //是否是调课
    tabsList:[],
    postData:{},
    allData:{}, //所有数据
    showDateSelect:false,
    defaultDateStr:"",
    currentDate: new Date().getTime(),
    defaultDate:[],
    coursePlanList:[],
    courseProcessList:[],
    selectDateText:{
      year:0,
      month:0
    },
    dateRangeList:[], //请假调课范围
    formatter(type:string, value:number) {      
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    qjCourseList:[]
  },
  
  // 打开日期选择框
  openDateSelect(){
   this.setData({
     showDateSelect:true
   })
  },
  // 关闭日期选择框
  onClose(){
    this.setData({
      showDateSelect:false
    })
  },
  // 确认选择的日期
  confirm(event:any) {
    this.setData({
      currentDate: event.detail,
      showDateSelect:false,
      courseProcessList:[]
    });
    this.timeFormatDate()
    // 请假调课选择时间不会刷新课程表
    if(this.data.dateRangeList.length < 2){
      this.getClassList()
    }
    
  },
  //时间戳转化为年月
  timeFormatDate(){
  let newDate = new Date(this.data.currentDate)
  let year = newDate.getFullYear()
  let month = newDate.getMonth() + 1
  const postData = this.data.postData as any
  postData.year = year
  postData.month = month
  this.setData({
    selectDateText:{
      year,
      month
    },
    postData
  })
  },
  // 查看所选择时间得课程
  selectCoursePlan(e:any){    
    this.setData({
      defaultDateStr:e.detail[0]
    })
    this.getCurrentDateList()
  },
  // 查询当前日期的课程列表
  getCurrentDateList(){
    const currentDate = this.data.defaultDateStr
    if(currentDate && this.dateProcessPlanMiddle(currentDate).length > 0){ 
   const courseProcessList = [
     {
      dateTime:currentDate,
      newList:this.dateProcessPlanMiddle(currentDate)
     }
   ] as any
   
     this.setData({
      courseProcessList
    })
    
    }else{
      this.setData({
        courseProcessList:[]
      })
    }
  },
  // 请假调课集合函数
  dateProcessPlanMiddle(currentDate:string){
    const allDate = this.data.allData as any
    if(allDate.length > 0) {
      const selectDateList = allDate.filter((val:{lessonDate:string})=>{
        return  val.lessonDate === currentDate
      })
       const courseProcessList = selectDateList.reduce((curr:any,val:any)=>{
        let existing = curr.find((item:{time:string}) => item.time === val.lessonStartTime);
        if(existing){
          existing.plan.push({
            courseName:val.courseSerialName,
            classRoom:val.roomName
          })
        }else{
          curr.push({
            time:val.lessonStartTime,
            plan:[{
              courseName:val.courseSerialName,
              classRoom:val.roomName,
              checked:this.data.leaveCourseList && this.data.leaveCourseList.includes(val.courseId),
              courseId:val.courseId,
              signState:val.signState,
              lessonState:val.lessonState,
              courseSerialCover:val.courseSerialCover,
              lessonId:val?.lessonId || "",
              instructorUsername:val.instructorUsername,
              courseType:val.courseType
            }]
          })
        }
        return curr
        },[] as Array<any>) 
        return courseProcessList
    }else{
      return []
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(data:any) {
    //调课
   if(data.leaveDate){
   const dateRangeList =  data.leaveDate.split(" ~ ")
    this.setData({
      dateRangeList,
      stuId:data.stuId,
      isTk:true
    })
   }
   this.timeFormatDate()
   if(!this.data.isTk){
    this.getTabList()
   }else{   
    this.setData({
      leaveCourseList:data.review
    })
     
   }
   this.getClassList()

  },
  //学生列表
  getTabList(){
  if(getApp().getUserType() === "01") return
  const memberList = getApp().getMemberList()
  const tabsList = memberList.map((val:{stuId:number,userName:string})=>{
    return {
      id:val.stuId,
      label:val.userName
    }
  })
  tabsList.unshift({
    id:0,
    label:"全部"
  })
  this.setData({
    tabsList
  })
  },
  // 获取课程表
  async getClassList(){
  const dateRangeList = this.data.dateRangeList as Array<number>
  const flag = dateRangeList.length < 2
  const {code,data:res}  = flag ? await getClassList(this.data.postData) :await getClassListForRange({
    startDate:dateRangeList[0] + '',
    endDate:dateRangeList[1] + '',
    stuId:this.data.stuId
  })
  if(code === 200){
    try {
      const defaultDate = res.map((val:{lessonDate:string})=>{
        return val.lessonDate
      })
      this.setData({
        defaultDate,
        allData:res
      })
      if(this.data.isTk){
         this.getQjCourseList()
      }else{
        this.getCurrentDateList()

      }
    } catch (error) {
      console.log("错误:",error);
    }
  }
  },
  // 切换学员
  handleChange(e:any){
    const postData = this.data.postData as any
   if(e.detail === 0){
    delete postData.stuId
   }else{
    postData.stuId = e.detail 
   }
   this.getClassList()
  },
  // 获取请假调课课程表内容
  getQjCourseList(){
    const dateRangeList = this.data.dateRangeList
    const  rangeDetaList = this.getDatesBetween(dateRangeList[0],dateRangeList[1])
    const qjCourseList = rangeDetaList.reduce((curr:any,val)=>{
    const newList = this.dateProcessPlanMiddle(val)
    curr.push({
      dateTime:val,
      newList
    })
    return curr
    },[])
    this.setData({
      courseProcessList:qjCourseList
    })
    
  },
  // 获取开始时间到结束时间中间得日期
  getDatesBetween(startDate:string, endDate:string) {
    const start = new Date(startDate); // 转换为 Date 对象
    const end = new Date(endDate);
    const dates = [];
    while (start <= end) {
      // 格式化日期为 YYYY-MM-DD
      const formattedDate = start.toISOString().split('T')[0];
      dates.push(formattedDate);
  
      // 日期增加一天
      start.setDate(start.getDate() + 1);
    }
  
    return dates;
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})